<?php namespace models;
/**
 * This code is property of Piotr Poradzisz. Do not distribute under threat of legal consequences.
 * All rights reserved.
 * Все права защищены.
 * Alle Rechte vorbehalten.
 * Todos los derechos reservados.
 * Wszelkie prawa zastrzeżone.
 *                  جميع الحقوق محفوظة
 * 保留所有权利
 * すべての著作権
 * @author Piotr Poradzisz
 * email: piotr.poradzisz@gmail.com
 * tel.: +48668027020
 */
class Menu{

    public $rootMenuId;

    private $menuSeries;

    public $menu;

    public $orientation = 'h'; // Horizontal/Vertical

    public function getMenu($menuId) {
        if($_SESSION['user']['userType'] == 1) $this->rootMenuId = 1;
        else if($_SESSION['user']['userType'] == 2) $this->rootMenuId = 2;
        $mysql = new Mysql();
        $menu = $mysql->getRow("SELECT * FROM menu WHERE id = $menuId");
        $_SESSION['query']['from'] = $menu['tableName'];
        $_SESSION['navigation'] = $menu;
        $this->setMenuSeries($menuId);
        $this->getMenuTree();
    }

    private function getMenuTree($key = 0, $level = 0) {
        if(isset($this->menuSeries[$key])){
            $menuId = $this->menuSeries[$key];
            $mysql = new Mysql();
            if(isset($this->menuSeries[$key+1])){
                $nextMenuId = $this->menuSeries[$key+1];
                $marked = ", IF(id = $nextMenuId, 1, 0) as marked";
            }
            $children = $mysql->getTable("SELECT * $marked FROM menu WHERE parent = $menuId");
            if($this->orientation == 'h'){
                $this->menu[$level] = $children;
                $this->getMenuTree(++$key, ++$level);
            }
            else{
                foreach($children as $childeKey => $childe){
                    if(isset($this->menuSeries[$key+1]) and $this->menuSeries[$key+1] == $childe['id']){
                        $childe['level'] = $level;
                        $this->menu[] = $childe;
                        $this->getMenuTree(++$key, ++$level);
                    }
                    else{
                        $childe['level'] = $level-1;
                        $this->menu[] = $childe;
                    }
                }
            }            
        }
    }

    private function setMenuSeries($parentMenuId){
        $this->menuSeries[] = $parentMenuId;
        if($parentMenuId >= $this->rootMenuId){
            $mysql = new Mysql();
            $parentMenuId = $mysql->getRecord("SELECT parent FROM menu WHERE id = $parentMenuId");
            $this->setMenuSeries($parentMenuId);
        }
        else $this->menuSeries = array_reverse($this->menuSeries);
    }
}
?>